<template>

  <!-- 头部 -->
  <van-sticky>
    <div class="L-bizcalendar-heard">
      <vue-hash-calendar show-arrow model="inline" ref="calendar" @change="handleChange" :default-datetime="new Date()"
        :themeColor="themeColor" markType="dot" week-start="Sunday" :markDate="markList"
        first-day-of-month-class-name="first-day-of-month-class-name" :disabled-week-view="true"
        :show-today-button="false" :is-show-time-picker="false" pickerType="date">
        <template v-slot:day="scope">
          <span style="font-weight: bold;">{{ scope?.date?.day }}</span>
        </template>
        <template #arrow="scope">
          <van-icon v-show="scope?.isShowWeek" class="arrowSZ" name="arrow-down" />
          <van-icon v-show="!scope?.isShowWeek" class="arrowSZ" name="arrow-up" />
        </template>
      </vue-hash-calendar>
    </div>
  </van-sticky>

  <!-- 排序 -->

  <div class="L-bizcalendar-sort">
    <van-popover v-model:show="showSortPopover" placement="bottom-end" :actions="sortOptions"
      @select="handleSortSelect">
      <template #reference>
        <span class="L-small-text">{{ currentSort.text }} <i class="iconfont" :class="'icon-xiangxia'"></i> </span>
      </template>
    </van-popover>
  </div>

  <!-- 列表 -->
  <div class="L-bizcalendar-list" style="padding-top:30px">

    <van-empty v-if="loading === false && list.length === 0" description="没有数据" />

    <!-- 骨架屏 -->
    <div v-if="loading">
      <van-skeleton title :row="3" v-for="item in 5" :key="item" style="margin-bottom:30px" />
    </div>

    <van-row :gutter="10" v-for="(item, index) in list" :key="index">
      <van-col :span="1" class="L-line-col">
        <div class="line-dot"></div>
      </van-col>
      <van-col :span="2">
        <div class="L-type-block">{{ item.object === 'bfpj' ? '协' : '拜' }}</div>
      </van-col>
      <van-col :span="21" style="padding-bottom: 20px;">
        <div>
          <span>{{ item.sname }}</span>
        </div>
        <div>
          <span class="L-small-text L-secondary-text-color L-margin-top-10">{{ item.saddress }}</span>
          <span class="L-secondary-text-color"
            style="margin-left: 10px;margin-right: 10px;font-size:14px">距我{{ item.distance }}m</span>
          <span style="color:#1c71fb;font-size:14px" @click="handleNavigation(item)">导航</span>
        </div>
        <van-row type="flex" justify="space-between" align="center">
          <van-col class="L-secondary-text-color L-mini-text">
            负责人:{{ item.contact }}
          </van-col>
          <van-col>
            <template v-if="item.scenario">
              <span v-if="item.scenario.scenario_ended === 0" class="L-schedule-btn" @click="handleSignIn(item)">签到</span>
              <span v-else-if="item.scenario.scenario_ended < item.scenario.scenario_total" class="L-schedule-btn"
                @click="handleSignOut(item)">签退</span>
              <span v-else class="L-schedule-btn" @click="handleSignOut(item)">详情</span>
            </template>

          </van-col>
        </van-row>
        <van-divider />
      </van-col>

    </van-row>
  </div>

  <!-- 地图弹窗 -->
  <van-popup round v-model:show="showeMapPopup" position="bottom" style="width: 100%;height:90%">
    <Map v-if="showeMapPopup" :map-data="currentMapInfo"></Map>
  </van-popup>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive, onActivated } from "vue";
import { apiConfigurable } from "@/request/api/api";
import { closeToast, showLoadingToast } from "vant";
import Map from "@/components/base/Map/Map.vue";
import { isTemplateTail } from "typescript";
import { useRouter } from "vue-router";
const router = useRouter();

const themeColor = {
  "bg-color": "#ffffff",
  "main-color": "#1677ff",
  "main-font-color": "#333333",
  "vice-font-color": "#666666",
  "disabled-bg-color": "#000",
  "disabled-font-color": "#aaa",
};

//
function handleSignIn(item) {

  const { scenario, object, id } = item;
  const { scenarioInfo, scenario_ended } = scenario;
  const query = {
    idobject: object,
    itemid: id,
    stitle: item.type,
  };

  router.push({
    path: "/bizcalendarAction",
    query,
  });
}

function handleSignOut(item) {
  const { scenario, object, id } = item;

  const query = {
    idobject: object,
    itemid: id,
    stitle: item.type,
  };

  router.push({
    path: "/defaultCard",
    query,
  });

}

// 地图=============================
interface mapInfo {
  name: string;
  address: string;
  lat: string | number;
  lng: string | number;
}

const showeMapPopup = ref(false);
const currentMapInfo = reactive<mapInfo>({
  name: "",
  address: "",
  lat: "",
  lng: "",
});

function handleNavigation(item) {
  currentMapInfo.name = item.sname;
  currentMapInfo.address = item.saddress;
  currentMapInfo.lat = item.lonlat.split(",")[1];
  currentMapInfo.lng = item.lonlat.split(",")[0];
  showeMapPopup.value = true;
}

// 排序==============================
const showSortPopover = ref(false);
interface sortOption {
  value: string;
  text: string;
}
const currentSort = reactive<sortOption>({
  value: "time_asc",
  text: "从近到远",
});
const sortOptions = [
  { value: "distance_asc", text: "从近到远" },
  { value: "distance_desc", text: "由远到近" },
  { value: "time_asc", text: "时间升序" },
  { value: "time_desc", text: "时间降序" },
];

function handleSortSelect(action: sortOption) {
  currentSort.text = action.text;
  currentSort.value = action.value;
}

watch(currentSort, (val) => {
  list.value = list.value.sort((a, b) => {
    switch (val.value) {
      case "time_asc":
        return Date.parse(a.created) - Date.parse(b.created);

      case "time_desc":
        return Date.parse(b.created) - Date.parse(a.created);

      case "distance_asc":
        return a.distance - b.distance;

      case "distance_desc":
        return b.distance - a.distance;
    }
  });
});

//日历============================
const currentDay = ref("");

function formatDate(date: Date) {
  var year = date.getFullYear();
  var month = addZero(date.getMonth() + 1);
  var day = addZero(date.getDate());
  return year + "-" + month + "-" + day;
}

function addZero(num: number) {
  return num < 10 ? "0" + num : num;
}

function handleChange(value: Date) {
  currentDay.value = formatDate(value);
}

watch(currentDay, () => {
  getData();
});

function getlocation() {
  // return new Promise((resolve, reject) => {
  //   let ua = window.navigator.userAgent.toLowerCase();
  //   let logintype = "wechat";
  //   let tourl = window.location.href;
  //   let clttype = "android";
  //   if (ua.indexOf("iphone") !== -1) {
  //     clttype = "ios";
  //   }
  //   // if (ua.indexOf('wxwork') !== -1 || ua.indexOf('micromessenger') !== -1) {
  //   // } else {
  //   //   logintype = 'dingding'
  //   //   tourl = window.location.protocol + '//' + window.location.host + '/vue-common/dist/main'
  //   // }
  //   if (ua.indexOf("wxwork") !== -1) {
  //     logintype = "wxwork";
  //   } else if (ua.indexOf("dingtalk") !== -1) {
  //     logintype = "dingding";
  //     // tourl = window.location.protocol + '//' + window.location.host + '/vue-common/dist/main'
  //   } else if (ua.indexOf("micromessenger") !== -1) {
  //     logintype = "wechat";
  //   } else if (ua.indexOf("tenantid") !== -1) {
  //     // 友空间
  //     logintype = "ykj";
  //   } else {
  //     logintype = "browser";
  //   }
  //   if (logintype === "browser") {
  //     // Toast("请在钉钉或微信端登录!");
  //     // TODO remove
  //     // this.$router.go(-1)
  //     this.center = [116.417913, 40.069559];
  //   }
  //   let _this = this;
  //   let data = {
  //     url: tourl,
  //     type: logintype,
  //     clttype: clttype,
  //   };
  //   let url = "/api/" + this.idobject + ".getlocation.do";
  //   this.axios({
  //     method: "post",
  //     url: url,
  //     data: qs.stringify(data),
  //   })
  //     .then((res) => {
  //       let data = res.data;
  //       if (logintype === "wechat" || logintype === "wxwork") {
  //         wx.config({
  //           beta: true,
  //           debug: false,
  //           appId: data.appId,
  //           timestamp: data.timestamp,
  //           nonceStr: data.nonceStr,
  //           signature: data.signature,
  //           jsApiList: ["getLocation"],
  //         });
  //         wx.ready(function () {
  //           wx.getLocation({
  //             isHighAccuracy: true,
  //             type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
  //             success: function (res) {
  //               var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
  //               var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
  //               _this.center[0] = res.longitude;
  //               _this.center[1] = res.latitude;
  //               _this.sort(latitude, longitude, "wx");
  //               console.log("wx success: ", res);
  //             },
  //             fail: function (err) {
  //               alert("微信定位失败，请检查定位是否已经打开!");
  //               console.log("wx fail: ", err);
  //             },
  //           });
  //         });
  //       } else if (logintype === "dingding") {
  //         dd.config({
  //           agentId: data.agentid,
  //           corpId: data.appId,
  //           timeStamp: data.timestamp,
  //           nonceStr: data.nonceStr,
  //           signature: data.signature,
  //           type: 0,
  //           jsApiList: ["device.geolocation.get"],
  //         });
  //         dd.error(function (error) {
  //           Toast("dd error: " + JSON.stringify(error));
  //         });
  //         dd.ready(function () {
  //           dd.device.geolocation.get({
  //             targetAccuracy: 200,
  //             coordinate: 1,
  //             withReGeocode: false,
  //             useCache: true,
  //             onSuccess: function (res) {
  //               console.log("this.center  res", res);
  //               var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
  //               var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
  //               _this.center = [res.longitude, res.latitude];
  //               // _this.center[0] = res.longitude
  //               // _this.center[1] = res.latitude
  //               _this.sort(latitude, longitude, "dd");
  //               resolve();
  //             },
  //             onfail: function (err) {
  //               alert("定位失败，请检查定位是否已经打开!");
  //               console.log(JSON.stringify(err));
  //             },
  //           });
  //         });
  //       } else if (logintype === "ykj") {
  //         YYEsnBridge.ready(function () {
  //           YYEsnBridge.do("getLocationInfo", {
  //             agentId: data.agentid,
  //             timeStamp: data.timestamp,
  //             signature: data.signature,
  //             success: function (res) {
  //               let longitude = res.longitude;
  //               let latitude = res.latitude;
  //               _this.sort(latitude, longitude, "YYEsnBridge");
  //             },
  //             fail: function (err) {
  //               alert("调用失败,请检查定位是否已经打开!" + JSON.stringify(err));
  //               console.log(JSON.stringify(err));
  //             },
  //             complete: function (res) {
  //               // alert('调用完成后执行');
  //               console.log("调用完毕:" + JSON.stringify(res));
  //             },
  //           });
  //         });
  //       }
  //     })
  //     .catch(function (error) {
  //       reject(error);
  //     });
  // });
}
// 列表============================
const loading = ref(false);

interface markItem {
  color: string;
  date: [string];
}

const Color = {
  red: "#ea6733",
  green: "#006a73",
  yellow: "#f6c034",
};

const markList = ref<markItem[] | []>([]);
const list = ref([]);

onMounted(() => { });
onActivated(() => {
  getData()
})

function getData() {
  loading.value = true;
  const url = "bizcalendar.fetchdata.do";
  const data = {
    bizcalendar_sort: currentSort.value,
    bizcalendar_date: currentDay.value,
    bizcalendar_longitude: "",
    bizcalendar_latitude: "",
  };
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(url, data)
    .then((res) => {
      if (res.code === 0) {
        const marks = res.data.marks;
        markList.value = Object.keys(marks).map((item) => {
          const markItem: markItem = {
            color: Color[item],
            date: marks[item],
          };
          return markItem;
        });
        list.value = res.data.targetmarks;
        closeToast();
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
</script>

<style scoped>
.L-line-col {
  border-left: 1px solid #eee;
  position: relative;
  
}

.L-line-col .line-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #eee;
  position: absolute;
  left: -5px;
  top: 8px;
}

.L-type-block {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: #1c71fb;
  display: flex;
  align-items: center;
  justify-content: center;

  color: #cddbfb;
  font-size: 12px;
  font-weight: bold;
  margin-right: 10px;
}

.first-day-of-month-class-name {
  font-size: 3.7333333333333vw;
}

.L-bizcalendar-heard {
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.L-bizcalendar-sort {
  margin: 15px auto;
  padding-right: 10px;
  text-align: right;
}

.L-bizcalendar-list {
  background: #fff;
  padding: 20px;
  /* min-height: 100vh; */
}
</style>